import 'package:flutter/material.dart';
import 'package:get/get.dart';
import '../controllers/alert_logs_controller.dart';
import 'package:intl/intl.dart';
import '../../../models/alert_log_model.dart';
import '../../../repositories/data_repository.dart';
import '../../../services/product_service.dart';
import '../../../services/device_service.dart';
import '../../../translations/app_translations.dart';

class AlertLogsView extends GetView<AlertLogsController> {
  const AlertLogsView({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(LocaleKeys.alertLogs.tr),
        actions: [
          IconButton(
            icon: const Icon(Icons.filter_list),
            onPressed: () => _showFilterDialog(context),
          ),
          IconButton(
            icon: const Icon(Icons.refresh),
            onPressed: () => controller.refreshData(),
          ),
        ],
      ),
      body: RefreshIndicator(
        onRefresh: controller.refreshData,
        child: Obx(() {
          if (controller.isLoading.value && controller.alertLogs.isEmpty) {
            return const Center(
              child: CircularProgressIndicator(),
            );
          }
          
          if (controller.alertLogs.isEmpty) {
            return Center(
              child: Column(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  const Icon(
                    Icons.notifications_off,
                    size: 80,
                    color: Colors.grey,
                  ),
                  const SizedBox(height: 16),
                  Text(
                    LocaleKeys.noAlertLogs.tr,
                    style: const TextStyle(
                      fontSize: 18,
                      color: Colors.grey,
                    ),
                  ),
                  const SizedBox(height: 8),
                  TextButton(
                    onPressed: () => controller.clearFilters(),
                    child: Text(LocaleKeys.clearFilters.tr),
                  ),
                ],
              ),
            );
          }
          
          return _buildAlertLogsList();
        }),
      ),
    );
  }
  
  Widget _buildAlertLogsList() {
    return ListView.builder(
      itemCount: controller.alertLogs.length + 1,
      itemBuilder: (context, index) {
        if (index == controller.alertLogs.length) {
          return _buildLoadMoreIndicator();
        }
        
        final alertLog = controller.alertLogs[index];
        return Card(
          margin: const EdgeInsets.symmetric(horizontal: 12, vertical: 6),
          child: InkWell(
            onTap: () => _showAlertLogDetail(context, alertLog.logId!),
            child: Padding(
              padding: const EdgeInsets.all(12.0),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Row(
                    children: [
                      Container(
                        padding: const EdgeInsets.symmetric(
                          horizontal: 8,
                          vertical: 4,
                        ),
                        decoration: BoxDecoration(
                          color: controller.getAlertLevelColor(alertLog.level),
                          borderRadius: BorderRadius.circular(4),
                        ),
                        child: Text(
                          alertLog.getLevelDesc(),
                          style: const TextStyle(
                            color: Colors.white,
                            fontSize: 12,
                            fontWeight: FontWeight.bold,
                          ),
                        ),
                      ),
                      const SizedBox(width: 8),
                      Container(
                        padding: const EdgeInsets.symmetric(
                          horizontal: 8,
                          vertical: 4,
                        ),
                        decoration: BoxDecoration(
                          color: controller.getAlertStatusColor(alertLog.status),
                          borderRadius: BorderRadius.circular(4),
                        ),
                        child: Text(
                          alertLog.getStatusDesc(),
                          style: const TextStyle(
                            color: Colors.white,
                            fontSize: 12,
                            fontWeight: FontWeight.bold,
                          ),
                        ),
                      ),
                      const Spacer(),
                      if (alertLog.status != 2) // 不是已确认状态
                        TextButton.icon(
                          icon: const Icon(Icons.check_circle_outline, size: 18),
                          label: Text(LocaleKeys.confirm.tr),
                          style: TextButton.styleFrom(
                            padding: const EdgeInsets.symmetric(
                              horizontal: 8,
                              vertical: 0,
                            ),
                            minimumSize: Size.zero,
                            tapTargetSize: MaterialTapTargetSize.shrinkWrap,
                          ),
                          onPressed: () => controller.confirmAlert(alertLog.logId!),
                        ),
                    ],
                  ),
                  const SizedBox(height: 8),
                  Text(
                    alertLog.alertName ?? LocaleKeys.unnamedAlert.tr,
                    style: const TextStyle(
                      fontSize: 16,
                      fontWeight: FontWeight.bold,
                    ),
                  ),
                  const SizedBox(height: 4),
                  Text(
                    alertLog.content ?? '',
                    style: const TextStyle(
                      fontSize: 14,
                      color: Colors.black87,
                    ),
                    maxLines: 2,
                    overflow: TextOverflow.ellipsis,
                  ),
                  const SizedBox(height: 8),
                  Row(
                    children: [
                      const Icon(
                        Icons.developer_board,
                        size: 16,
                        color: Colors.grey,
                      ),
                      const SizedBox(width: 4),
                      Text(
                        alertLog.deviceName ?? LocaleKeys.unknownDevice.tr,
                        style: const TextStyle(
                          fontSize: 12,
                          color: Colors.grey,
                        ),
                      ),
                      const SizedBox(width: 12),
                      const Icon(
                        Icons.category,
                        size: 16,
                        color: Colors.grey,
                      ),
                      const SizedBox(width: 4),
                      Text(
                        alertLog.productName ?? LocaleKeys.unknownProduct.tr,
                        style: const TextStyle(
                          fontSize: 12,
                          color: Colors.grey,
                        ),
                      ),
                    ],
                  ),
                  const SizedBox(height: 4),
                  Row(
                    children: [
                      const Icon(
                        Icons.access_time,
                        size: 16,
                        color: Colors.grey,
                      ),
                      const SizedBox(width: 4),
                      Text(
                        _formatDateTime(alertLog.alertTime),
                        style: const TextStyle(
                          fontSize: 12,
                          color: Colors.grey,
                        ),
                      ),
                    ],
                  ),
                ],
              ),
            ),
          ),
        );
      },
    );
  }
  
  Widget _buildLoadMoreIndicator() {
    return Obx(() {
      if (controller.isLoadingMore.value) {
        return const Padding(
          padding: EdgeInsets.all(16.0),
          child: Center(
            child: CircularProgressIndicator(),
          ),
        );
      }
      
      if (!controller.hasMore.value) {
        return Padding(
          padding: const EdgeInsets.all(16.0),
          child: Center(
            child: Text(
              LocaleKeys.noMoreData.tr,
              style: const TextStyle(color: Colors.grey),
            ),
          ),
        );
      }
      
      return Padding(
        padding: const EdgeInsets.all(16.0),
        child: Center(
          child: TextButton(
            onPressed: controller.loadMore,
            child: Text(LocaleKeys.loadMore.tr),
          ),
        ),
      );
    });
  }
  
  void _showFilterDialog(BuildContext context) {
    // 临时变量保存当前过滤条件
    int? selectedLevel = controller.level.value;
    int? selectedStatus = controller.status.value;
    String? alertNameFilter = controller.alertName.value;
    String? deviceSnFilter = controller.deviceSn.value;
    DateTimeRange? selectedDateRange = controller.dateRange.value;
    
    showDialog(
      context: context,
      builder: (context) => StatefulBuilder(
        builder: (context, setState) {
          return AlertDialog(
            title: Text(LocaleKeys.filterAlertLogs.tr),
            content: SingleChildScrollView(
              child: Column(
                mainAxisSize: MainAxisSize.min,
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text(
                    LocaleKeys.alertLevel.tr,
                    style: const TextStyle(fontWeight: FontWeight.bold),
                  ),
                  Wrap(
                    spacing: 8,
                    children: [
                      _buildFilterChip(
                        label: LocaleKeys.all.tr,
                        selected: selectedLevel == null,
                        onSelected: (selected) {
                          setState(() {
                            selectedLevel = null;
                          });
                        },
                      ),
                      _buildFilterChip(
                        label: LocaleKeys.alertLevelInfo.tr,
                        selected: selectedLevel == 1,
                        onSelected: (selected) {
                          setState(() {
                            selectedLevel = selected ? 1 : null;
                          });
                        },
                      ),
                      _buildFilterChip(
                        label: LocaleKeys.alertLevelWarning.tr,
                        selected: selectedLevel == 2,
                        onSelected: (selected) {
                          setState(() {
                            selectedLevel = selected ? 2 : null;
                          });
                        },
                      ),
                      _buildFilterChip(
                        label: LocaleKeys.severe.tr,
                        selected: selectedLevel == 3,
                        onSelected: (selected) {
                          setState(() {
                            selectedLevel = selected ? 3 : null;
                          });
                        },
                      ),
                      _buildFilterChip(
                        label: LocaleKeys.critical.tr,
                        selected: selectedLevel == 4,
                        onSelected: (selected) {
                          setState(() {
                            selectedLevel = selected ? 4 : null;
                          });
                        },
                      ),
                    ],
                  ),
                  const SizedBox(height: 16),
                  Text(
                    LocaleKeys.alertStatus.tr,
                    style: const TextStyle(fontWeight: FontWeight.bold),
                  ),
                  Wrap(
                    spacing: 8,
                    children: [
                      _buildFilterChip(
                        label: LocaleKeys.all.tr,
                        selected: selectedStatus == null,
                        onSelected: (selected) {
                          setState(() {
                            selectedStatus = null;
                          });
                        },
                      ),
                      _buildFilterChip(
                        label: LocaleKeys.alertStatusGenerated.tr,
                        selected: selectedStatus == 0,
                        onSelected: (selected) {
                          setState(() {
                            selectedStatus = selected ? 0 : null;
                          });
                        },
                      ),
                      _buildFilterChip(
                        label: LocaleKeys.alertStatusRecovered.tr,
                        selected: selectedStatus == 1,
                        onSelected: (selected) {
                          setState(() {
                            selectedStatus = selected ? 1 : null;
                          });
                        },
                      ),
                      _buildFilterChip(
                        label: LocaleKeys.alertStatusConfirmed.tr,
                        selected: selectedStatus == 2,
                        onSelected: (selected) {
                          setState(() {
                            selectedStatus = selected ? 2 : null;
                          });
                        },
                      ),
                    ],
                  ),
                  const SizedBox(height: 16),
                  TextField(
                    decoration: InputDecoration(
                      labelText: LocaleKeys.alertName.tr,
                      border: const OutlineInputBorder(),
                      isDense: true,
                    ),
                    controller: TextEditingController(text: alertNameFilter),
                    onChanged: (value) {
                      alertNameFilter = value.isEmpty ? null : value;
                    },
                  ),
                  const SizedBox(height: 12),
                  TextField(
                    decoration: InputDecoration(
                      labelText: LocaleKeys.serialNumber.tr,
                      border: const OutlineInputBorder(),
                      isDense: true,
                    ),
                    controller: TextEditingController(text: deviceSnFilter),
                    onChanged: (value) {
                      deviceSnFilter = value.isEmpty ? null : value;
                    },
                  ),
                  const SizedBox(height: 16),
                  Text(
                    LocaleKeys.timeRange.tr,
                    style: const TextStyle(fontWeight: FontWeight.bold),
                  ),
                  const SizedBox(height: 8),
                  Row(
                    children: [
                      Expanded(
                        child: TextButton(
                          onPressed: () async {
                            final DateTimeRange? result = 
                                await showDateRangePicker(
                              context: context,
                              firstDate: DateTime(2022),
                              lastDate: DateTime.now(),
                              initialDateRange: selectedDateRange,
                            );
                            if (result != null) {
                              setState(() {
                                selectedDateRange = result;
                              });
                            }
                          },
                          child: Text(
                            selectedDateRange == null
                                ? LocaleKeys.selectDateRange.tr
                                : '${DateFormat('yyyy-MM-dd').format(selectedDateRange!.start)} ${LocaleKeys.to.tr} ${DateFormat('yyyy-MM-dd').format(selectedDateRange!.end)}',
                          ),
                        ),
                      ),
                      if (selectedDateRange != null)
                        IconButton(
                          icon: const Icon(Icons.clear),
                          onPressed: () {
                            setState(() {
                              selectedDateRange = null;
                            });
                          },
                        ),
                    ],
                  ),
                ],
              ),
            ),
            actions: [
              TextButton(
                onPressed: () {
                  controller.clearFilters();
                  Navigator.of(context).pop();
                },
                child: Text(LocaleKeys.clear.tr),
              ),
              TextButton(
                onPressed: () => Navigator.of(context).pop(),
                child: Text(LocaleKeys.cancel.tr),
              ),
              ElevatedButton(
                onPressed: () {
                  controller.applyFilters(
                    level: selectedLevel,
                    status: selectedStatus,
                    alertName: alertNameFilter,
                    deviceSn: deviceSnFilter,
                    dateRange: selectedDateRange,
                  );
                  Navigator.of(context).pop();
                },
                child: Text(LocaleKeys.apply.tr),
              ),
            ],
          );
        },
      ),
    );
  }
  
  Widget _buildFilterChip({
    required String label,
    required bool selected,
    required Function(bool) onSelected,
  }) {
    return FilterChip(
      label: Text(label),
      selected: selected,
      onSelected: onSelected,
      selectedColor: Colors.blue.withOpacity(0.2),
    );
  }
  
  void _showAlertLogDetail(BuildContext context, int logId) async {
    final dataRepository = Get.find<DataRepository>();
    final productService = Get.find<ProductService>();
    final deviceService = Get.find<DeviceService>();
    
    final result = await showDialog(
      context: context,
      builder: (context) => FutureBuilder<AlertLogDetailResponse>(
        future: dataRepository.getAlertLogDetail(logId),
        builder: (context, snapshot) {
          if (snapshot.connectionState == ConnectionState.waiting) {
            return const AlertDialog(
              content: Center(
                child: CircularProgressIndicator(),
              ),
            );
          }
          
          if (snapshot.hasError) {
            return AlertDialog(
              title: Text(LocaleKeys.error.tr),
              content: Text('${LocaleKeys.loadAlertDetailFailed.tr}: ${snapshot.error}'),
              actions: [
                TextButton(
                  onPressed: () => Navigator.of(context).pop(),
                  child: Text(LocaleKeys.close.tr),
                ),
              ],
            );
          }
          
          final alertDetail = snapshot.data!;
          var alertLog = alertDetail.data;
          
          if (alertLog == null) {
            return AlertDialog(
              title: Text(LocaleKeys.notFound.tr),
              content: Text(LocaleKeys.alertLogNotFound.tr),
              actions: [
                TextButton(
                  onPressed: () => Navigator.of(context).pop(),
                  child: Text(LocaleKeys.close.tr),
                ),
              ],
            );
          }
          
          // 使用FutureBuilder处理设备和产品信息的异步加载
          return FutureBuilder<AlertLog>(
            future: _enrichAlertLogWithInfo(alertLog, deviceService, productService),
            builder: (context, enrichedSnapshot) {
              // 如果数据还在加载中，显示一个加载动画
              if (enrichedSnapshot.connectionState == ConnectionState.waiting) {
                return const AlertDialog(
                  content: Center(
                    child: CircularProgressIndicator(),
                  ),
                );
              }
              
              // 使用补充了信息的告警日志，如果加载失败则使用原始日志
              final enrichedLog = enrichedSnapshot.data ?? alertLog;
            
              return AlertDialog(
                title: Row(
                  children: [
                    Container(
                      padding: const EdgeInsets.symmetric(
                        horizontal: 8,
                        vertical: 4,
                      ),
                      decoration: BoxDecoration(
                        color: controller.getAlertLevelColor(enrichedLog.level),
                        borderRadius: BorderRadius.circular(4),
                      ),
                      child: Text(
                        enrichedLog.getLevelDesc(),
                        style: const TextStyle(
                          color: Colors.white,
                          fontSize: 12,
                          fontWeight: FontWeight.bold,
                        ),
                      ),
                    ),
                    const SizedBox(width: 8),
                    Expanded(
                      child: Text(
                        enrichedLog.alertName ?? LocaleKeys.unnamedAlert.tr,
                        style: const TextStyle(fontSize: 18),
                      ),
                    ),
                  ],
                ),
                content: SingleChildScrollView(
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    mainAxisSize: MainAxisSize.min,
                    children: [
                      _buildDetailRow(LocaleKeys.deviceName.tr, enrichedLog.deviceName ?? LocaleKeys.unknown.tr),
                      _buildDetailRow(LocaleKeys.productName.tr, enrichedLog.productName ?? LocaleKeys.unknown.tr),
                      _buildDetailRow(LocaleKeys.serialNumber.tr, enrichedLog.deviceSn ?? LocaleKeys.unknown.tr),
                      _buildDetailRow(LocaleKeys.productKey.tr, enrichedLog.productKey ?? LocaleKeys.unknown.tr),
                      _buildDetailRow(LocaleKeys.propertyIdentifier.tr, enrichedLog.propertyIdentifier ?? LocaleKeys.unknown.tr),
                      _buildDetailRow(LocaleKeys.propertyValue.tr, enrichedLog.propertyValue ?? LocaleKeys.unknown.tr),
                      _buildDetailRow(LocaleKeys.alertStatus.tr, enrichedLog.getStatusDesc()),
                      _buildDetailRow(LocaleKeys.alertTime.tr, _formatDateTime(enrichedLog.alertTime)),
                      if (enrichedLog.recoverTime != null)
                        _buildDetailRow(LocaleKeys.recoveryTime.tr, _formatDateTime(enrichedLog.recoverTime)),
                      if (enrichedLog.confirmTime != null) ...[
                        _buildDetailRow(LocaleKeys.confirmationTime.tr, _formatDateTime(enrichedLog.confirmTime)),
                        _buildDetailRow(LocaleKeys.confirmationUser.tr, enrichedLog.confirmUser ?? LocaleKeys.unknown.tr),
                      ],
                      const Divider(),
                      Text(
                        '${LocaleKeys.alertContent.tr}:',
                        style: const TextStyle(fontWeight: FontWeight.bold),
                      ),
                      const SizedBox(height: 4),
                      Text(enrichedLog.content ?? LocaleKeys.noContent.tr),
                    ],
                  ),
                ),
                actions: [
                  if (enrichedLog.status != 2) // 不是已确认状态
                    TextButton.icon(
                      icon: const Icon(Icons.check_circle_outline),
                      label: Text(LocaleKeys.confirmAlert.tr),
                      onPressed: () async {
                        final success = await controller.confirmAlert(logId);
                        if (success) {
                          Navigator.of(context).pop(true);
                        }
                      },
                    ),
                  TextButton(
                    onPressed: () => Navigator.of(context).pop(),
                    child: Text(LocaleKeys.close.tr),
                  ),
                ],
              );
            },
          );
        },
      ),
    );
    
    if (result == true) {
      // 如果告警已确认，刷新列表
      controller.refreshData();
    }
  }
  
  // 补充告警日志的设备和产品信息
  Future<AlertLog> _enrichAlertLogWithInfo(
    AlertLog log, 
    DeviceService deviceService, 
    ProductService productService
  ) async {
    // 如果告警日志中已有设备名称和产品名称且不为空，则直接返回
    if ((log.deviceName != null && log.deviceName!.isNotEmpty && log.deviceName != LocaleKeys.unknown.tr) && 
        (log.productName != null && log.productName!.isNotEmpty && log.productName != LocaleKeys.unknown.tr)) {
      return log;
    }
    
    var enrichedLog = log;
    
    // 从缓存中查找设备信息
    if (log.deviceId != null) {
      final device = await deviceService.getDeviceById(log.deviceId!);
      if (device != null) {
        enrichedLog = enrichedLog.copyWith(
          deviceName: device.deviceName ?? LocaleKeys.unknownDevice.tr,
          deviceSn: device.deviceSn ?? LocaleKeys.unknown.tr
        );
      }
    }
    
    // 从缓存中查找产品信息
    if (log.productId != null) {
      final product = await productService.getProductById(log.productId!);
      if (product != null) {
        enrichedLog = enrichedLog.copyWith(
          productName: product.productName ?? LocaleKeys.unknownProduct.tr
        );
      }
    }
    
    return enrichedLog;
  }
  
  Widget _buildDetailRow(String label, String value) {
    return Padding(
      padding: const EdgeInsets.only(bottom: 8.0),
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          SizedBox(
            width: 80,
            child: Text(
              '$label:',
              style: const TextStyle(
                fontWeight: FontWeight.bold,
                color: Colors.black54,
              ),
            ),
          ),
          Expanded(
            child: Text(
              value,
              style: const TextStyle(
                color: Colors.black87,
              ),
            ),
          ),
        ],
      ),
    );
  }
  
  String _formatDateTime(String? dateTimeStr) {
    if (dateTimeStr == null || dateTimeStr.isEmpty) {
      return LocaleKeys.unknown.tr;
    }
    
    try {
      // 尝试解析日期时间字符串
      final DateTime dateTime = DateTime.parse(dateTimeStr);
      return DateFormat('yyyy-MM-dd HH:mm:ss').format(dateTime);
    } catch (e) {
      // 如果解析失败，直接返回原始字符串
      return dateTimeStr;
    }
  }
} 